2164. Julius Caesar Cyfer

 

Julius Caesar used his own method of encrypting text. Each letter is replaced by the following in alphabetical order by k positions in the circle. Given an encrypted text. Determine its original text.

 

Input. The first line contains the encrypted text containing no more than 255 Latin capital letters. The second line contains integer k (1 ≤ k ≤ 10).

 

Output. Print the result of decoding.

 

Sample input

Sample output

XPSE

1

WORD

 

 

SOLUTION

strings

 

Algorithm analysis

To decipher, each letter must be scrolled k positions back in a circle. Lets numerate the letters from 0 (‘A’) to 25 (‘Z’).

Let s[i] be the current letter of the cipher. Then the number of the letter is s[i] – ‘A’. Subtract the value of k from it in a circle (before ‘A’ comes ‘Z’), we get (s[i] – ‘A’ – k + 26) % 26. It remains to add ‘A’ to it, getting the ASCII code. Thus, the decryption operation looks like this:

s[i] = (s[i] – ‘A’ – k + 26) % 26 + ‘A’

 

Algorithm realization

Declare a character array s to store an input string there.

 

char s[1000];

 

Read the input data.

 

gets(s); scanf("%d", &k);

 

Decrypt the characters of the string according to the cipher.

 

for (i = 0; i < strlen(s); i++)

  s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

 

Print the result of decryption.

 

puts(s);

 

Algorithm realization – STL

 

#include <iostream>

#include <string>

using namespace std;

 

string s;

int i, k;

 

int main(void)

{

  cin >> s >> k;

  for (i = 0; i < s.size(); i++)

    s[i] = (((s[i] - 'A') + 26 - k) % 26) + 'A';

  cout << s << endl;

  return 0;

}